urls.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import os
  2. import sys
  3. from pip._vendor.six.moves.urllib import parse as urllib_parse
  4. from pip._vendor.six.moves.urllib import request as urllib_request
  5. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  6. if MYPY_CHECK_RUNNING:
  7. from typing import Optional, Text, Union
  8. def get_url_scheme(url):
  9. # type: (Union[str, Text]) -> Optional[Text]
  10. if ':' not in url:
  11. return None
  12. return url.split(':', 1)[0].lower()
  13. def path_to_url(path):
  14. # type: (Union[str, Text]) -> str
  15. """
  16. Convert a path to a file: URL. The path will be made absolute and have
  17. quoted path parts.
  18. """
  19. path = os.path.normpath(os.path.abspath(path))
  20. url = urllib_parse.urljoin('file:', urllib_request.pathname2url(path))
  21. return url
  22. def url_to_path(url):
  23. # type: (str) -> str
  24. """
  25. Convert a file: URL to a path.
  26. """
  27. assert url.startswith('file:'), (
  28. "You can only turn file: urls into filenames (not {url!r})"
  29. .format(**locals()))
  30. _, netloc, path, _, _ = urllib_parse.urlsplit(url)
  31. if not netloc or netloc == 'localhost':
  32. # According to RFC 8089, same as empty authority.
  33. netloc = ''
  34. elif sys.platform == 'win32':
  35. # If we have a UNC path, prepend UNC share notation.
  36. netloc = '\\\\' + netloc
  37. else:
  38. raise ValueError(
  39. 'non-local file URIs are not supported on this platform: {url!r}'
  40. .format(**locals())
  41. )
  42. path = urllib_request.url2pathname(netloc + path)
  43. return path